//1.导入模块
import http from 'wechat-http'
//2.配置及地址
http.baseURL = 'https://live-api.itheima.net'
http.timeout = 5000
/**
 * 配置请求拦截器
 */
http.intercept.request = (params) => {
  //获取token 
  const token = getApp().token
  if (token) {
    // console.log(res);
    params.header = {
      'Authorization': `Bearer ${token}`,
      ...params.token
    };
  }
  return params
}
//3.配置响应拦截器
http.intercept.response = async (res) => {
  if (res.data.code === 401) {
    if (res.config.url.includes('/refreshToken')) {
      //提示用户
      wx.utils.toast('请重新登录')
      const pageStack = getCurrentPages()
      //获取当前页面路径
      const currentPage = pageStack[pageStack.length - 1]
      //接路径
      const redirect = currentPage.route
      //跳转页面
      return wx.redirectTo({
        url: `/pages/login/index?redirectUrl=/${redirect}`,
      })
    }
    const app = getApp()
    // console.log(2222222, app.ref_token)
    const ref = await http({
      url: '/refreshToken',
      method: 'POST',
      header: {
        Authorization: `Bearer ${wx.getStorageSync('ref_token')}`
      }
    })
    // console.log(ref, '000');
    app.setToken(ref.data.token, ref.data.refreshToken)
    res.config.header = {
      Authorization: `Bearer ${wx.getStorageSync('token')}`
    }
    return http(res.config)
  } else if (res.data.code !== 10000) {
    wx.showToast({
      title: res.data.message,
      mask: true,
      icon: 'error'
    })
    return Promise.reject(res)
  }
  // 过滤接口返回的数据
  return res.data
}
wx.http = http
export default http